#!/usr/bin/python
# -*- coding: utf-8 -*-
# author: yoshiii.yoshiii@googlemail.com
# you found this code on http://yoshiii-box.googlecode.com/svn/ 
#

import os, sys
import socket
import time

config	= os.path.expanduser("~/.yoshiii-share.cfg")
cfg	= {}
hosts	= []
pwd	= ""

def access_granted(path):
	path = os.path.abspath(path)
	for item in cfg["shares"]:
		if path.startswith(item): return True
	return False

def cmd_pwd(request):
	global pwd
	pwd = os.popen("pwd").read()[:-1]
	return pwd

def cmd_ls(request):
	args = request.split()[1:]
	result = ""
	if len(args) == 0: args.append(".")
	for arg in args:
		path = os.path.abspath(pwd + os.sep + arg)
		if access_granted(path):
			cmd = "ls %s"%path
			result += os.popen(cmd).read()
		else:
			result += path + " access denied"
	return result

def cmd_cd(request):
	arg = request.split()[1]
	path = os.path.abspath(pwd + os.sep + arg)
	if access_granted(path):
		os.chdir(path)
		result = cmd_pwd(None)
	else:
		result = path + "access denied"
	return result

def cmd_help(request):
	commands = cmds.keys()
	commands.sort()
	return ", ".join(commands)

def cmd_get(request):
	arg = request.split()[1]
	path = os.path.abspath(pwd + os.sep + arg)
	try:
		if access_granted(path):
			result = open(path, "r").read()
		else:
			result = path + "access denied"
		return result
	except IOError, e:
		return e

cmds = {
		"pwd"	: cmd_pwd,
		"ls"	: cmd_ls,
		"cd"	: cmd_cd,
		"help"	: cmd_help,
		"get"   : cmd_get,
}

def serve(input, output):
	while input:
		try:
			print >> output, cfg["prompt"][0], 
			request = input.readline()
			result = cmds[request.split()[0]](request)
			print >> output, result
		except KeyError, e:
			print >> output, "unknown command:", e, "\ntype 'help' for command list"

def __init__():
	config_file = open(os.path.abspath(config)).readlines()
	cfg["shares"] = ["",]
	cfg["prompt"] = ["> ",]
	for line in config_file:
		key, value = line.split(":")
		cfg[key] = value.split()
	print "cfg:", cfg
	
	cmd_pwd(None)
	

def main():
	__init__()
	try:
		serve(sys.stdin, sys.stdout)
	except KeyboardInterrupt:	# if Ctrl+c
		pass
	except IndexError:	# if Ctrl+d
		pass


if __name__ == '__main__':
	main()
